package com.dayu.web.controller.recovery;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dayu.common.annotation.RepeatSubmit;
import com.dayu.common.core.domain.entity.SysDictData;
import com.dayu.recovery.domain.RecoveryData;
import com.dayu.recovery.domain.export.BillAndCollectExport;
import com.dayu.security.web.service.PermissionService;
import com.dayu.system.service.ISysDictDataService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dayu.common.annotation.Log;
import com.dayu.common.core.controller.BaseController;
import com.dayu.common.core.domain.AjaxResult;
import com.dayu.common.enums.BusinessType;
import com.dayu.recovery.domain.RecoveryBill;
import com.dayu.recovery.service.IRecoveryBillService;
import com.dayu.common.utils.poi.ExcelUtil;
import com.dayu.common.core.page.TableDataInfo;

/**
 * 财务账单Controller
 * 
 * @author HK
 * @date 2021-04-16
 */
@RestController
@RequestMapping("/recovery/bill")
public class RecoveryBillController extends BaseController
{
    @Autowired
    private IRecoveryBillService recoveryBillService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询财务账单列表
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:list')")
    @GetMapping("/list")
    public TableDataInfo list(RecoveryBill recoveryBill) throws ParseException {
        hasBillListAll(recoveryBill);
        startPage();
        List<RecoveryBill> list = recoveryBillService.selectRecoveryBillList(recoveryBill);
        return getDataTable(list);
    }

    /**
     * 销售私人查看列表
     * @param recoveryBill
     * @return
     * @throws ParseException
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:sells')")
    @GetMapping("/sell/list")
    public TableDataInfo sellList(RecoveryBill recoveryBill) throws ParseException {
        hasBillListAll(recoveryBill);
        startPage();
        List<RecoveryBill> list = recoveryBillService.selectRecoveryBillBySellList(recoveryBill);
        return getDataTable(list);
    }

    /**
     * 合计
     * @param recoveryBill
     * @return
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:sum')")
    @GetMapping("/list/sum")
    public AjaxResult dataPrice(RecoveryBill recoveryBill) throws ParseException {
        hasBillListAll(recoveryBill);
        RecoveryData recoveryData = recoveryBillService.selectRecoveryData(recoveryBill);
        return AjaxResult.success(recoveryData);
    }
    /**
     * 导出财务账单列表
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:export')")
    @Log(title = "财务账单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(RecoveryBill recoveryBill) throws ParseException {
        hasBillListAll(recoveryBill);
        List<BillAndCollectExport> list = recoveryBillService.selectRecoveryBillListExport(recoveryBill);
        for(BillAndCollectExport bill : list) {
            if(bill.getPaymentType() == 4 || bill.getPaymentType() == 6) {
                bill.tranPaymentDetailExcl(dictDataService);
            }
            bill.totalPriceAdd();
            bill.setExportCompany();
        }
        ExcelUtil<BillAndCollectExport> util = new ExcelUtil<>(BillAndCollectExport.class);
        return util.exportExcel(list, "bill");
    }

    /**
     * 获取财务账单详细信息
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:query')")
    @GetMapping(value = "/{billId}")
    public AjaxResult getInfo(@PathVariable("billId") Long billId)
    {
        return AjaxResult.success(recoveryBillService.selectRecoveryBillById(billId));
    }

    /**
     * 新增财务账单
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('recovery:bill:add')")
    @Log(title = "财务账单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RecoveryBill recoveryBill)
    {
        return toAjax(recoveryBillService.insertRecoveryBill(recoveryBill));
    }

    /**
     * 修改财务账单
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:edit')")
    @Log(title = "财务账单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RecoveryBill recoveryBill)
    {
        return toAjax(recoveryBillService.updateRecoveryBill(recoveryBill));
    }

    @PreAuthorize("@ss.hasPermi('recovery:bill:edit')")
    @Log(title = "财务账单批量审核", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{billIds}")
    public AjaxResult editStatus(@PathVariable Long[] billIds) {
        return toAjax(recoveryBillService.updateRecoveryBillByList(billIds));
    }

    /**
     * 删除财务账单
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:remove')")
    @Log(title = "财务账单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{billIds}")
    public AjaxResult remove(@PathVariable Long[] billIds)
    {
        return toAjax(recoveryBillService.deleteRecoveryBillByIds(billIds));
    }

    /**
     * 批量出售
     * @param list
     * @return
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('recovery:bill:sell')")
    @Log(title = "批量出售", businessType = BusinessType.INSERT)
    @PostMapping("/add/list")
    public AjaxResult insertList(@RequestBody List<RecoveryBill> list){
        if(list == null || list.size() == 0) {
            return AjaxResult.error("没有数据哦！");
        }
        return toAjax(recoveryBillService.sellGoodsByList(list));
    }

    /**
     * 退货操作
     * @param recoveryBill
     * @return
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('recovery:bill:out')")
    @Log(title = "商品退货", businessType = BusinessType.INSERT)
    @PostMapping("/out/goods")
    public AjaxResult billOutGoods(@RequestBody RecoveryBill recoveryBill) {
        RecoveryBill bill = recoveryBillService.selectRecoveryBillById(recoveryBill.getBillId());
        if(bill.getType() != 1) {
            return AjaxResult.error("只有账单类型为'商品出售'的才可以退货！");
        }
        if(bill.getStatus() == 3) {
            return AjaxResult.error("这条财务账单的商品已经退过了，请勿重复退货！");
        }
        if(bill.getGoodsId() == null) {
            return AjaxResult.error("找不到退货商品！");
        }
        return toAjax(recoveryBillService.returnGoodsByBill(recoveryBill));
    }

    /**
     *  条件统计 筛选 获得支付方式
     * @param reqMap
     * @return
     */
    @PreAuthorize("@ss.hasPermi('recovery:bill:condition')")
    @PostMapping("/condition")
    public AjaxResult paymentDataMap(@RequestBody Map<String, Object> reqMap) {
        List<Map<String, Object>> respList = recoveryBillService.conditionSearch(reqMap);
        return AjaxResult.success(respList);
    }

    private void hasBillListAll(RecoveryBill bill) throws ParseException {
        boolean bool = permissionService.hasPermi("bill:list:all");
        if(bool) {
            return;
        }
        SysDictData dictData = new SysDictData();
        dictData.setDictType("bill_list_date");
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        String month = list.get(0).getDictValue();
        long sends = 1000L * 60 * 60 * 24 * (30 * Integer.parseInt(month)); //一个月默认30天
        long newTime = new Date().getTime();
        /*查询条件中params不为空 */
        if(bill.getParams() != null) {
            /*params中 startTime 不为空*/
            if(bill.getParams().get("createStartTime") != null) {
                /*查询时间如果小于，最小查询日期，将会赋值为最小查询日期*/
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date selTime = dateFormat.parse(bill.getParams().get("createStartTime").toString());
                Date startTime = (newTime - sends) > selTime.getTime() ? new Date(newTime - sends) : selTime;
                bill.getParams().put("createStartTime", startTime);
                return;
            }
            bill.getParams().put("createStartTime", new Date(newTime - sends));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("createStartTime", new Date(newTime - sends));
        bill.setParams(map);
    }
}
